/**
 * 
 */
package com.wubo.sec.service.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wubo.common.util.Assert;
import com.wubo.common.util.ObjectUtils;
import com.wubo.sec.SecurityManager;
import com.wubo.sec.config.LangUtil;
import com.wubo.sec.event.EntityEvent;
import com.wubo.sec.event.GroupEvent;
import com.wubo.sec.log.LogHelper;
import com.wubo.sec.model.Group;
import com.wubo.sec.service.IGroupService;
import com.wubo.sec.util.ObjectDifferenceChecker;
import com.wubo.sec.util.UUID;
import com.wubo.spring.hibernate.BaseHibernateDao;

/**
 * @author WuBo
 * @CreateDate 2010-8-2
 * @version 1.0.01
 */
@Service
@SuppressWarnings("unchecked")
public class GroupService implements IGroupService {

	private static Log logger = LogFactory.getLog(GroupService.class);
	private BaseHibernateDao dao;
	
	public BaseHibernateDao getDao() {
		return dao;
	}
	@Autowired
	public void setDao(BaseHibernateDao dao) {
		this.dao = dao;
	}
	
	/* (non-Javadoc)
	 * @see com.asc.sf.service.IGroupService#findAccessibleGroups(int, java.lang.String)
	 */
	public List<Group> findAccessibleGroups(int priority, String mark, Group group) {
		dao.setCacheQueries(true);
		if(group.isMarkLocked()){
			return dao.find("select g from Group g where g.priority < ? and g.mark = ?", new Object[]{priority, mark});
		}else{
			return dao.find("select g from Group g where g.priority < ?", new Object[]{priority});
		}
	}
	public String create(Group group) {
		if(group.getCode() == null){
			group.setCode(UUID.uuid());
		}
		if(group.getPriority() <= 0){ //组级别如果小于0，则置为中级
			group.setPriority(Group.MID);
		}

		if(logger.isDebugEnabled()){
			logger.debug("Create a group:"+ObjectUtils.objToString(group));
		}
		
		java.util.Date now = new java.util.Date();
		String username = SecurityManager.getCurrentUser().getUsername();
		group.setCreateTime(now);
		group.setCreateUser(username);
		group.setUpdateTime(now);
		group.setUpdateUser(username);
		
		onAdd(group);
		
		String code = (String) dao.save(group);
		
		afterAdd(group);
		
		return code;
	}
	
	public void delete(Group group) {
		Assert.notNull(group);
		
		onDelete(group);
		
		dao.delete(group);
		
		afterDelete(group);
	}
	
	public List<Group> findAll() {
		return dao.find("from Group g");
	}
	
	public List<Group> find(String filter, Object[] params){
		return dao.find("select g from Group g "+filter, params);
	}
	
	public List<Group> findRunAs(String filter, Object[] params){
		return find(filter, params);
	}
	
	public List<Group> getSplitPage(int start, int limit, String filter, Object... params) {
		return dao.queryForPage(start, limit, "select g from Group g "+filter, params);
	}
	
	public long getTotal(String filter, Object... params) {
		Long result = dao.queryForObject("select count(g.code) from Group g "+filter, params);
		return result;
	}
	
	public Group get(String code) {
		return dao.get(Group.class, code);
	}
	
	public Group update(Group group) {
		Group temp = get(group.getCode());
		
		Group old = temp.clone();
		
		temp.setName(group.getName());
		temp.setDesn(group.getDesn());
		temp.setMark(group.getMark());
		temp.setMarkLocked(group.isMarkLocked());
		temp.setPriority(group.getPriority());
		
		java.util.Date now = new java.util.Date();
		String username = SecurityManager.getCurrentUser().getUsername();
		temp.setUpdateTime(now);
		temp.setUpdateUser(username);
		
		if(logger.isDebugEnabled()){
			logger.debug("Update a group:"+ObjectUtils.objToString(group));
		}
		
		onUpdate(temp);
		dao.update(temp);
		afterUpdate(old, temp);
		
		return temp;
	}

	public List<String[]> listName(String name) {
		return dao.find("select g.code,g.name from Group g where g.code like '%"+name+"%' or g.name like '%"+name+"%'");
	}
	
	//按标识来查询
	public List<String[]> listMark(String mark){
		return dao.find("select g.mark from Group g where g.mark like '%"+mark+"%'");
	}

	/*----- 发布事件  -----*/
	protected void onAdd(Group group){
		SecurityManager.publishEvent(new GroupEvent(group, EntityEvent.ADD));
	}
	protected void onUpdate(Group group){
		SecurityManager.publishEvent(new GroupEvent(group, EntityEvent.UPDATE));
	}
	protected void onDelete(Group group){
		SecurityManager.publishEvent(new GroupEvent(group, EntityEvent.DELETE));
	}
	/*----- 记录日志 -----*/
	protected void afterAdd(Group group){
		LogHelper.actionLog(LangUtil.get("CreateGroup"), 
				LangUtil.get("GroupDetail", group.getCode(), ObjectUtils.objToString(group)));
	}
	protected void afterUpdate(Group old, Group group){
		LogHelper.actionLog(LangUtil.get("UpdateGroup"), 
				LangUtil.get("UpdateGroupDetail", ObjectDifferenceChecker.check(old, group)));
	}
	protected void afterDelete(Group group){
		LogHelper.actionLog(LangUtil.get("DeleteGroup"), 
				LangUtil.get("GroupDetail", ObjectUtils.objToString(group)));
	}
}
